// search.js
 
const elasticsearch = require('elasticsearch');
 
const client = new elasticsearch.Client({
    host: 'xxx',
    log: 'error'
});
 
const search = function search(index, body) {
    return client.search({index: index, body: body});
};

 export function searchData(size, from, _index_dex) {
    let body = {
        size,
        from,
        query: {
            match_all: {}
        }
    };
 
    search(_index_dex, body)
        .then(results => {
            console.log(`found ${results.hits.total.value} items in ${results.took}ms`);
            console.log(`returned:`,results.hits);
            results.hits.hits.forEach(
                (hit, index) => console.log(
                    console.log(hit._source)
                )
            )
        })
        .catch(console.error);
      }

export function bulkIndex(index, type, data) {
  let bulkBody = [];

  data.forEach(item => {
      bulkBody.push({
          index: {
              _index: index,
              _type: type,
              _id: item.id
          }
      });

      bulkBody.push(item);
  });

  client.bulk({body: bulkBody})
      .then(response => {
          let errorCount = 0;
          response.items.forEach(item => {
              if (item.index && item.index.error) {
                  console.log(++errorCount, item.index.error);
              }
          });
          console.log(
              `[${new Date()}] - Successfully indexed ${data.length - errorCount}
        out of ${data.length} items`
          );
      })
      .catch(e => {
        console.log(e)
        process.exit()
      });
};

function indices() {
  return client.cat.indices({v: true})
  .then(console.log)
  .catch(err => console.error(`Error connecting to the es client: ${err}`));
}

export function verify() {
  console.log(`elasticsearch indices information:`);
  indices();
}